/*
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum ingilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package cn.itenzo.common.validate;

import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

/**
 * 长度校验
 * 
 * @author ENZO
 *
 */
public class LengthValidate extends ValidatorHandler<String> implements Validator<String> {

	private int min = 0;
	private int max = Integer.MAX_VALUE;
	private String fileName;

	/**
	 * 长度校验
	 * @param min 最小长度
	 * @param max 最大长度
	 * @param fileName 错误的字段名称
	 */
	public LengthValidate(int min, int max, String fileName) {
		this.min = min;
		this.max = max;
		this.fileName = fileName;
	}

	@Override
	public boolean validate(ValidatorContext context, String t) {
		if (null == t || t.length() > max || t.length() < min) {
			if(null == t){
				context.addErrorMsg(String.format("%s,为空", fileName == null ? "字段名" : fileName));
				return false;
			}
			if(min == max)
				context.addErrorMsg(String.format("%s,长度为%d", fileName, min, max));
			else
				context.addErrorMsg(String.format("%s,长度在%d-%d之间", fileName, min, max));
			return false;
		}
		return true;

	}

	@Override
	public boolean accept(ValidatorContext context, String t) {
		return super.accept(context, t);
	}

}
